<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use think\facade\Log;
use app\service\{LearningService, AiChatService, AiService};
use Exception;

class LearningController extends BaseController
{
    protected $learningService;
    protected $aiChatService;

    public function __construct()
    {
        $this->learningService = new LearningService();
        $this->aiChatService = new AiChatService();
    }

    /**
     * 智能学习对话接口
     * POST /learning/chat
     */
    public function chat(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $result = $this->learningService->handleLearningChat($user, [
                'content' => $request->post('content'),
                'element_id' => $request->post('element_id'),
                'session_id' => $request->post('session_id'),
                'message_id' => $request->post('message_id'),
                'teaching_plan_id' => $request->post('teaching_plan_id'),
                'course_id' => $request->post('course_id'),
                'learning_mode' => $request->post('learning_mode', 'training'),
                'ai_role_id' => $request->post('ai_role_id')
            ]);

            return json([
                'status' => 200,
                'message' => '处理成功',
                'data' => $result
            ]);
        } catch (Exception $e) {
            Log::error('学习对话处理失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '处理失败：' . $e->getMessage()]);
        }
    }

    /**
     * 学习流式响应接口
     * GET /learning/stream
     */
    public function stream(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');
            header('X-Accel-Buffering: no');
            
            // 复用现有流式响应逻辑
            $result = $this->aiChatService->handleStreamResponse(
                $request->param('message_id'),
                $user
            );

            $aiService = new AiService();
            $fullContent = '';
            
            $aiService->streamChat($result['history'], function($chunk) use (&$fullContent) {
                $fullContent .= $chunk;
                echo "data: " . json_encode([
                    'content' => $chunk,
                    'done' => false
                ], JSON_UNESCAPED_UNICODE) . "\n\n";
                ob_flush();
                flush();
            }, $result['sessionInfo']);

            $result['aiMessage']->content = $fullContent;
            $result['aiMessage']->save();
            
            echo "data: " . json_encode([
                'content' => '',
                'done' => true
            ]) . "\n\n";
            
        } catch (Exception $e) {
            Log::error('学习流式响应失败：' . $e->getMessage());
            echo "data: " . json_encode([
                'error' => $e->getMessage(),
                'done' => true
            ]) . "\n\n";
        }
    }

    /**
     * 学习会话初始化接口
     * POST /learning/session/init
     */
    public function initSession(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $result = $this->learningService->initLearningSession($user, [
                'course_id' => $request->post('course_id'),
                'teaching_plan_id' => $request->post('teaching_plan_id'),
                'element_id' => $request->post('element_id'),
                'learning_mode' => $request->post('learning_mode', 'training')
            ]);

            return json([
                'status' => 200,
                'message' => '初始化成功',
                'data' => $result
            ]);
        } catch (Exception $e) {
            Log::error('学习会话初始化失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '初始化失败：' . $e->getMessage()]);
        }
    }

    /**
     * 学习进度查询接口
     * GET /learning/progress
     */
    public function progress(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $result = $this->learningService->getProgress($user, [
                'course_id' => $request->param('course_id'),
                'teaching_plan_id' => $request->param('teaching_plan_id'),
                'session_id' => $request->param('session_id')
            ]);

            return json([
                'status' => 200,
                'data' => $result
            ]);
        } catch (Exception $e) {
            Log::error('学习进度查询失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '查询失败：' . $e->getMessage()]);
        }
    }

    /**
     * 学习历史查询接口
     * GET /learning/history
     */
    public function history(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        try {
            $result = $this->learningService->getHistory($user, [
                'page' => $request->param('page', 1),
                'page_size' => $request->param('page_size', 10),
                'status' => $request->param('status')
            ]);

            return json([
                'status' => 200,
                'data' => $result
            ]);
        } catch (Exception $e) {
            Log::error('学习历史查询失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '查询失败：' . $e->getMessage()]);
        }
    }
}